package com.example.shuiyin.parsers;

import com.example.shuiyin.enums.MediaType;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class DouyinParser implements MediaParser {

    private final RestTemplate restTemplate = new RestTemplate();
    private static final Pattern URL_PATTERN = Pattern.compile("(https?://v\\.douyin\\.com/[a-zA-Z0-9]+)");
    private static final Pattern VIDEO_PATTERN = Pattern.compile("\"playAddr\":\"([^\"]+)\"");
    private static final Pattern TITLE_PATTERN = Pattern.compile("\"desc\":\"([^\"]+)\"");

    @Override
    public MediaInfo parse(String url) {
        try {
            // 1. 提取短链接
            Matcher matcher = URL_PATTERN.matcher(url);
            if (!matcher.find()) {
                throw new AppException("无效的抖音链接", ErrorCode.INVALID_PARAMETER);
            }
            String shortUrl = matcher.group(1);
            
            // 2. 获取重定向URL
            String redirectUrl = getRedirectUrl(shortUrl);
            
            // 3. 获取HTML内容
            ResponseEntity<String> response = restTemplate.getForEntity(redirectUrl, String.class);
            String html = response.getBody();
            
            if (html == null) {
                throw new AppException("无法获取抖音页面内容", ErrorCode.INTERNAL_ERROR);
            }
            
            // 4. 提取视频地址和标题
            Matcher videoMatcher = VIDEO_PATTERN.matcher(html);
            Matcher titleMatcher = TITLE_PATTERN.matcher(html);
            
            if (!videoMatcher.find() || !titleMatcher.find()) {
                throw new AppException("无法解析抖音视频信息", ErrorCode.INTERNAL_ERROR);
            }
            
            String videoUrl = videoMatcher.group(1).replace("\\u002F", "/");
            String title = titleMatcher.group(1);
            
            return new MediaInfo(title, videoUrl, MediaType.VIDEO);
        } catch (AppException e) {
            throw e;
        } catch (Exception e) {
            log.error("解析抖音链接失败: {}", e.getMessage(), e);
            throw new AppException("解析抖音链接失败: " + e.getMessage(), ErrorCode.INTERNAL_ERROR);
        }
    }

    @Override
    public boolean supports(String url) {
        return url != null && url.contains("douyin.com");
    }
    
    private String getRedirectUrl(String shortUrl) {
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    shortUrl, 
                    HttpMethod.GET, 
                    null, 
                    String.class
            );
            
            if (response.getStatusCode() == HttpStatus.FOUND || response.getStatusCode() == HttpStatus.MOVED_PERMANENTLY) {
                HttpHeaders headers = response.getHeaders();
                if (headers.getLocation() != null) {
                    return headers.getLocation().toString();
                }
            }
            
            throw new AppException("无法获取重定向URL", ErrorCode.INTERNAL_ERROR);
        } catch (Exception e) {
            log.error("获取重定向URL失败: {}", e.getMessage(), e);
            throw new AppException("获取重定向URL失败: " + e.getMessage(), ErrorCode.INTERNAL_ERROR);
        }
    }
}